package py.com.fms.com.session.transactions;

// External classes imports 
// Java Classes
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

// Seam Classes
import org.jboss.aspects.dbc.condition.parser.LoopExpression;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.richfaces.component.html.HtmlDatascroller;

import com.ibatis.sqlmap.client.SqlMapClient;

import javax.faces.application.FacesMessage;
import javax.faces.event.ActionEvent;
import javax.faces.validator.ValidatorException;

//project classes imports
import py.com.fms.com.bean.BuyConditionBean;
import py.com.fms.com.bean.FeesToSuppliersBean;
import py.com.fms.com.bean.OrderDetBean;
import py.com.fms.com.bean.OrderHeadBean;
import py.com.fms.com.bean.PaymentOrderDetBean;
import py.com.fms.com.bean.PaymentOrderHeadBean;
import py.com.fms.com.bean.PurchasesDetBean;
import py.com.fms.com.bean.PurchasesHeadBean;
import py.com.fms.com.bean.SupplyCostStockBean;

import py.com.fms.fms.bean.CurrencyBean;
import py.com.fms.fms.bean.EnterpriseBean;
import py.com.fms.fms.bean.GenParamBean;
import py.com.fms.fms.bean.MeasureUnitBean;
import py.com.fms.fms.bean.RefDetBean;
import py.com.fms.fms.bean.SupplierBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.bean.VoucherBean;
import py.com.fms.com.persistence.services.FeesToSupplierServices;
import py.com.fms.com.persistence.services.PurchasesServices;
import py.com.fms.com.persistence.services.OrderServices;
import py.com.fms.com.persistence.services.BuyConditionServices;
import py.com.fms.com.persistence.services.SupplyCostStockServices;
import py.com.fms.fms.persistence.services.CurrencyServices;
import py.com.fms.fms.persistence.services.EnterpriseServices;
import py.com.fms.fms.persistence.services.GenParamServices;
import py.com.fms.fms.persistence.services.IvaServices;
import py.com.fms.fms.persistence.services.MeasureUnitServices;
import py.com.fms.fms.persistence.services.QuotationServices;
import py.com.fms.fms.persistence.services.RefServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.fms.persistence.services.VoucherServices;
import py.com.fms.fms.session.maintenances.EditNumbers;
import py.com.fms.exception.CommonException;
import py.com.fms.session.ComAssistant;
import py.com.fms.session.ParamHolder;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.session.modalSelectHolder;
import py.com.fms.utilities.ConvertAssistant;
import py.com.fms.utilities.DateAssistant;
import py.com.fms.utilities.NullAssistant;

@SuppressWarnings("unused")
@Name("trnPurchase")
@Scope(ScopeType.SESSION)
public class TrnPurchase {

	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private boolean editMode;
	private String initVar;
	private Date today = null;

	// Task Attendees Attributes
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{paramHolder}")
	private ParamHolder param;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In("#{comAssist}")
	private ComAssistant comAssist;
	@In
	Credentials credentials;
	@In
	Identity identity;
	private UsersBean user;

	// Attribute used for saving and deleting
	private PurchasesHeadBean purchasesHead;
	private PurchasesDetBean purchasesDet;

	private OrderHeadBean orderHead;
	private OrderDetBean orderDet;
	private BuyConditionBean buyCondition;
	private EditNumbers numbers;

	// Grilla detalle
	private List<PurchasesDetBean> allPurchasesDet;
	private Collection<OrderDetBean> allOrderDet;

	// Services
	private EnterpriseServices enSrv;
	private PurchasesServices prSrv;
	private OrderServices orSrv;
	private BuyConditionServices bcSrv;
	private FeesToSupplierServices fsSrv;
	private IvaServices txSrv;
	private QuotationServices qtSrv;
	private CurrencyServices crSrv;
	private UsersServices usSrv;
	private VoucherServices vouSrv;
	private SupplyCostStockServices scstSrv;

	// Collection of monedasBean
	private Collection<BuyConditionBean> allBuyCondition;

	// For Query of all Orders
	private PurchasesHeadBean purchaseQueryHead;
	private PurchasesDetBean purchaseQueryDet;
	private Collection<PurchasesHeadBean> allPurchaseQueryHead;
	private Collection<PurchasesDetBean> allPurchaseQueryDet;

	// For Orders Cancellation
	private PurchasesHeadBean purchaseCancelHead;
	private PurchasesDetBean purchaseCancelDet;
	private Collection<PurchasesHeadBean> allPurchaseCancelHead;
	private Collection<PurchasesDetBean> allPurchaseCancelDet;

	// For Orders Confirmation
	private PurchasesHeadBean purchaseConfHead;
	private PurchasesDetBean purchaseConfDet;
	private Collection<PurchasesHeadBean> allPurchaseConfHead;
	private Collection<PurchasesDetBean> allPurchaseConfDet;

	private FeesToSuppliersBean feesToSupplierQuery;
	private Collection<FeesToSuppliersBean> allFeesToSupplierQuery;
	private PaymentOrderHeadBean feesToSupplierQueryData;
	private Collection<PaymentOrderDetBean> allFeesToSupplierQueryData;

	// Necessary Attributes;
	private static Boolean canSave;
	private EnterpriseBean entName = null;
	private EnterpriseBean entCod;
	private Long entId;
	private String operationType = "CNOR";
	private Boolean validateEntireForm = true;
	
	// RichFaces dataScroller variables
	private modalSelectHolder selectHolder;
	private HtmlDatascroller scroller = new HtmlDatascroller();
	private Integer scrollerPage = new Integer(0);
	private Boolean selectedAll = false;

	
	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] [[[[[[[[[[-------------]]]]]]]]]]
	 * 
	 * @throws CommonException
	 * Operation Types (Tipo de Operacion)
	 * -- CNOR = COMPRA NORMAL
	 * -- CPED = COMPRA A TRAVES DE PEDIDO
	 * -- NCRE = NOTA DE CREDITO
	 * 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			System.out.println("INITIALIZING DATA ------------------");
			this.loadUserData();
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();
			this.initQueryObjects();

		}
		this.setInitVar(null);
		System.out.println("OUT");

	}

	// public void loadParams() throws CommonException{
	// this.param.initData();
	// this.param.loadParams();
	// }

	private void loadUserData() throws CommonException {
		System.out.println("Iniciando usuario compra");
		if (user == null) {
			user = new UsersBean();
		}
		if (usSrv == null) {
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		System.out.println("Antes de credential");
		if (user != null && credentials != null) {
			System.out.println("Credenciales Encontradas: " + credentials + "User: " + user);
			this.getUser().setUserName(credentials.getUsername());
			System.out.println("User Name: " + this.getUser().getUserName());
			try {
				this.setUser(usSrv.getUserDataByName(this.getUser().getUserName().toUpperCase().trim()));
			} catch (Exception e) {
				System.out.println("ERROR: " + e.getMessage());
			}
			
			this.setUser(this.user);
			System.out.println("User: " + this.getUser());
			System.out.println("User ENT: " + this.getUser().getIdEnt());
			System.out.println("User BRANCH: " + this.getUser().getDefaultBranch());
		} else {
			System.out.println("Credenciales Nulas");
		}
		System.out.println("Despues de credentials");
	}

	public void initBeans() {
		System.out.println("Initializing Entities");
		if (purchasesHead == null) {
			purchasesHead = new PurchasesHeadBean();
			purchasesHead.setIdEnt(this.user.getIdEnt());
			purchasesHead.setIdBranch(this.user.getDefaultBranch());
			purchasesHead.setDiscount(new BigDecimal(0));
			purchasesHead.setCharge(new BigDecimal(0));
		}

		if (purchasesDet == null) {
			purchasesDet = new PurchasesDetBean();
		}

		if (orderHead == null) {
			orderHead = new OrderHeadBean();
		}

		if (orderDet == null) {
			orderDet = new OrderDetBean();
		}

		if (buyCondition == null) {
			buyCondition = new BuyConditionBean();
			buyCondition.setStatus(true);
		}

		if (entCod == null) {
			entCod = new EnterpriseBean();
		}

		if (entName == null) {
			entName = new EnterpriseBean();
		}
		
		if(selectHolder == null){
			selectHolder = new modalSelectHolder();
		}
		
		

	}

	public void initServices() throws CommonException {
		System.out.println("Initializing Services");
		if (vouSrv == null) {
			vouSrv = new VoucherServices(this.sqlMap.getConfig());
		}
		if (prSrv == null) {
			prSrv = new PurchasesServices(this.sqlMap.getConfig());
		}

		if (enSrv == null) {
			enSrv = new EnterpriseServices(this.sqlMap.getConfig());
		}

		if (orSrv == null) {
			orSrv = new OrderServices(this.sqlMap.getConfig());
		}

		if (bcSrv == null) {
			bcSrv = new BuyConditionServices(this.sqlMap.getConfig());
		}

		if (txSrv == null) {
			txSrv = new IvaServices(this.sqlMap.getConfig());
		}

		if (qtSrv == null) {
			qtSrv = new QuotationServices(this.sqlMap.getConfig());
		}

		if (crSrv == null) {
			crSrv = new CurrencyServices(this.sqlMap.getConfig());
		}

		if (fsSrv == null) {
			fsSrv = new FeesToSupplierServices(this.sqlMap.getConfig());
		}

		if(scstSrv == null){
		   scstSrv = new SupplyCostStockServices(this.sqlMap.getConfig());
		}
	}

	public void initAssistants() {
		System.out.println("Initializing Assistants");

		if (aid == null) {
			aid = new WithinHolder();
		}

		if (param == null) {
			param = new ParamHolder();
		}

		if (convert == null) {
			convert = new ConvertAssistant();
		}

		if (comAssist == null) {
			comAssist = new ComAssistant();
		}

		if (numbers == null) {
			numbers = new EditNumbers();
		}

		if (facesMessages == null) {
			this.facesMessages = new FacesMessages();
		}

	}

	public void initCollections() {
		System.out.println("Initializing Collections");
		if (allBuyCondition == null) {
			allBuyCondition = new ArrayList<BuyConditionBean>();
		}

		if (allPurchasesDet == null) {
			allPurchasesDet = new ArrayList<PurchasesDetBean>();
		}

		if (allOrderDet == null) {
			allOrderDet = new ArrayList<OrderDetBean>();
		}

	}

	/**
	 * Initialize Query objects
	 */
	public void initQueryObjects() {

		if (purchaseQueryHead == null) {
			purchaseQueryHead = new PurchasesHeadBean();
		}

		if (purchaseQueryDet == null) {
			purchaseQueryDet = new PurchasesDetBean();
		}

		if (allPurchaseQueryHead == null) {
			allPurchaseQueryHead = new ArrayList<PurchasesHeadBean>();
		}

		if (allPurchaseQueryDet == null) {
			allPurchaseQueryDet = new ArrayList<PurchasesDetBean>();
		}

		if (purchaseCancelHead == null) {
			purchaseCancelHead = new PurchasesHeadBean();
		}

		if (purchaseCancelDet == null) {
			purchaseCancelDet = new PurchasesDetBean();
		}

		if (allPurchaseCancelHead == null) {
			allPurchaseCancelHead = new ArrayList<PurchasesHeadBean>();
		}

		if (allPurchaseCancelDet == null) {
			allPurchaseCancelDet = new ArrayList<PurchasesDetBean>();
		}

		if (purchaseConfHead == null) {
			purchaseConfHead = new PurchasesHeadBean();
		}

		if (purchaseConfDet == null) {
			purchaseConfDet = new PurchasesDetBean();
		}

		if (allPurchaseConfHead == null) {
			allPurchaseConfHead = new ArrayList<PurchasesHeadBean>();
		}

		if (allPurchaseConfDet == null) {
			allPurchaseConfDet = new ArrayList<PurchasesDetBean>();
		}

		if (feesToSupplierQuery == null) {
			feesToSupplierQuery = new FeesToSuppliersBean();
		}

		if (allFeesToSupplierQuery == null) {
			allFeesToSupplierQuery = new ArrayList<FeesToSuppliersBean>();
		}
		
		if (feesToSupplierQueryData == null) {
			feesToSupplierQueryData = new PaymentOrderHeadBean();
		}

		if (allFeesToSupplierQueryData == null) {
			allFeesToSupplierQueryData = new ArrayList<PaymentOrderDetBean>();
		}


	}

	public void cleanData() {
		System.out.println("Cleaning Purchase Data");
		buyCondition = null;
		entCod = null;
		entName = null;
		user = null;

		enSrv = null;
		bcSrv = null;
		crSrv = null;
		qtSrv = null;
		txSrv = null;
		usSrv = null;
		orSrv = null;
		prSrv = null;
		vouSrv = null;
		scstSrv = null;

		aid = null;
		param = null;
		convert = null;
		comAssist = null;

		allBuyCondition = null;
		allOrderDet = null;
		orderDet = null;
		orderHead = null;

		purchasesHead = null;
		purchasesDet = null;
		allPurchasesDet = null;

		numbers = null;

	}

	// Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			this.setAllBuyCondition(bcSrv.getAllBuyCondition());
			for (BuyConditionBean buyCondition : this.getAllBuyCondition()) {
				System.out.println(buyCondition.getDescrip());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	// Used to cancel
	public void cancelData() throws CommonException {
		// this.facesMessages.clear();
		System.out.println("Canceling OPERATION ---------------------------");
		this.cleanData();
		this.setInitVar("S");
		this.initData();

	}
	
	public void selectAll(ActionEvent event) {
		System.out.println("SELECTING ALL CHECKBOXES");
		
		// get the current scroller page
		int page = Integer.valueOf(scrollerPage).intValue();
		if (page != 0) {
		    page = page - 1;
		}
		int start = page * 10;
		int stop = (page * 10) + 10;
		if (stop > this.getAllPurchasesDet().size()) {
		    stop = this.getAllPurchasesDet().size();
		}
		System.out.println("> page: " + page + "; start: " + start + "; stop: " + stop);
		System.out.println("Selected All: " + this.selectedAll);
		
		// check the boxes on the active page
		if(this.selectedAll == true){
			for (int i = start; i < stop; i++) {
				this.allPurchasesDet.get(i).setSelected(true);
			}
		}
		
		// uncheck the boxes on the active page
		if(this.selectedAll == false){
			for (int i = start; i < stop; i++) {
				this.allPurchasesDet.get(i).setSelected(false);
			}
		}
		
		
	}
	
	public void deleteSelected(){
		System.out.println("DELETING SELECTEDS");
		Iterator<PurchasesDetBean> it = this.allPurchasesDet.iterator();
		while(it.hasNext()){
			PurchasesDetBean next = it.next();
			if(next.getSelected().equals(true)){
				it.remove();
			}
		}
		if(this.selectedAll.equals(true)){
			this.setSelectedAll(false);
		}
		this.calcHeadAmounts();
		
	}

	public Boolean activeSupplyDepend() {

		if (this.getPurchasesDet().getSupplyData() == null) {
			System.out.println("RENDER TAX: TRUE");
			return true;
		} else {
			System.out.println("RENDER TAX: FALSE");
			return false;
		}
	}

	/**
	 * Habilita la lista de pedidos confirmados para un determinado proveedor
	 */
	public Boolean activeOrderQuery() {
		if (this.getPurchasesHead().getSupplierData() == null) {
			System.out.println("* activeOrderQuery RENDER ORDER QUERY: FALSE");
			return false;

		} else {
			if (aid.supplierOrdersList(this.getPurchasesHead().getSupplierData().getId()).isEmpty()) {
				System.out.println("** activeOrderQuery RENDER ORDER QUERY: FALSE");
				return false;
			} else {
				System.out.println("*** activeOrderQueryRENDER ORDER QUERY: TRUE");
				return true;
			}
		}

	}

	
	public void retrieveSupplyData() throws CommonException {
		System.out.println("RETRIEVING SUPPLY DATA");
		if (this.getPurchasesDet().getSupplyData() == null) {
			System.out.println("POR FAVOR ELIJA EL INSUMO");
		} else {
			Long taxId = new Long(0);
			taxId = this.getPurchasesDet().getSupplyData().getTax();
			this.getPurchasesDet().setTaxData(this.txSrv.getTaxData(taxId));
			if(this.getPurchasesDet().getMeasureUnitData() != null){
				this.retrieveSupplyCost();
			}
			System.out.println("TAX DATA: ".concat(this.getPurchasesDet().getTaxData().getId().toString()));
		}

	}

	public void retrieveChangeType() throws ParseException, CommonException {
		System.out.println("RETRIEVING CHANGE TYPE");
		// First we verify for null object
		if (this.getPurchasesHead().getCurrencyData() == null) {
			System.out.println("Currency Data is NULL");
		} else {
			// If object is not null
			// We retrieve the parameters
			Long localCurrency = this.crSrv.getIdCurrency("GUAR");
			Long idCurrency = this.getPurchasesHead().getCurrencyData().getId();
			if (idCurrency.equals(localCurrency)) {
				this.getPurchasesHead().setChangeType(new Double(1));
			} else {
				Date startDate = DateAssistant.getCurrentDate();
				System.out.println(" ##### CHANGE TYPE DATE: ".concat(startDate.toString()).concat(" ##### "));
				System.out.println(" ##### currency id = ".concat(idCurrency.toString()).concat(" ##### "));
				// Then we retrieve the changeType based on passed parameters
				Double changeType = (Double) this.qtSrv.getAmountQuotation(idCurrency, startDate);

				// And set the changeType value
				if (changeType == null) {
					FacesMessages.instance().add("La moneda seleccionada no tiene cotizaci�n para la fecha actual. Favor inserte cotizaci�n para la fecha.");
					this.getPurchasesHead().setChangeType(new Double(0));
				} else {
					this.getPurchasesHead().setChangeType(changeType);
					System.out.println("CHANGE TYPE: " + (this.getPurchasesHead().getChangeType()));
				}
			}
		}
	}
	
	public void retrieveSupplyCost(){
		if(this.getPurchasesDet().getSupplyData() == null || this.getPurchasesDet().getMeasureUnitData() == null){
			System.out.println("COST STOCK DATA Data is NULL");
		}else{
			try {
			// OOOOOOOOOOOJOOOOOOOOOOOOOOO SUCURSAL TRAER DEL FORMULARIOOOOOOOOOOOOOOOOOOOOOOOO
			Long supply = this.getPurchasesDet().getSupplyData().getId();
			Long branch = new Long(this.user.getDefaultBranch());
			Long measureUnit = this.getPurchasesDet().getMeasureUnitData().getId();
			// Retrieve Supply Cost Stock Data
			SupplyCostStockBean costStockData;
			costStockData = scstSrv.getSupplyCostStockData(supply, branch, measureUnit);
			if(costStockData != null){
				this.getPurchasesDet().setGrossCost(costStockData.getGrossCost());
			}else{
				this.getPurchasesDet().setGrossCost(null);
			}
			} catch (CommonException e) {
				// TODO Auto-generated catch block
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
		}
	}
	
	public void selectSupplier(SupplierBean supplier){
		System.out.println("Selecting Supplier");
		this.getPurchasesHead().setSupplierData(null);
		if(supplier.getCod() == null){
			comAssist.generateErrorMsg("Favor seleccione un proveedor", "actionForm:acceptSelectedSupplier");
		}else{
			System.out.println("Selecting Supplier: "+supplier.getCod());
			this.getPurchasesHead().setSupplierData(supplier);
		}	
	}

	/**
	 * Rellena los campos del formulario de compras si se ha seleccionado un
	 * pedido
	 */
	public void fillFromOrder() {
		try {
			if (this.getPurchasesHead().getOrderHeadData() != null) {

				// Cleaning Data
				this.getAllOrderDet().clear();
				this.getAllPurchasesDet().clear();

				// Filling the header
				this.getPurchasesHead().setBuyConditionData(convert.getBuyConditionData(this.getPurchasesHead().getOrderHeadData().getBuyCondition()));
				this.getPurchasesHead().setBuyTypeData(convert.getRefDetData(this.getPurchasesHead().getOrderHeadData().getBuyType()));
				this.getPurchasesHead().setCurrencyData(convert.getCurrencyData(this.getPurchasesHead().getOrderHeadData().getCurrency()));
				this.getPurchasesHead().setChangeType(this.getPurchasesHead().getOrderHeadData().getChangeType());
				this.getPurchasesHead().setCostCenterData(convert.getRefDetData(this.getPurchasesHead().getOrderHeadData().getCostCenter()));
				this.getPurchasesHead().setDiscount(this.getPurchasesHead().getOrderHeadData().getDiscount());

				// Filling details

				this.setAllOrderDet(orSrv.getOrderDetByHeadId(this
						.getPurchasesHead().getOrderHeadData().getId()));
				System.out.println("FILL FROM ORDER - ALL ORDERS: "
						+ this.getAllOrderDet());

				Iterator<OrderDetBean> it = this.allOrderDet.iterator();
				while (it.hasNext()) {
					OrderDetBean next = it.next();
					System.out.println("FILL FROM ORDER - NEXT: " + next);
					this.getPurchasesDet().setSupplyData(convert.getSupplyData(next.getSupply()));
					this.getPurchasesDet().setMeasureUnitData(convert.getMeasureUnitData(next.getMeasureUnit()));
					this.getPurchasesDet().setGrossCost(next.getGrossCost());
					this.getPurchasesDet().setOrderQuantity(next.getQuantity() - next.getInvoiceQuantities());
					this.getPurchasesDet().setQuantity(next.getQuantity() - next.getInvoiceQuantities());
					this.getPurchasesDet().setTaxData(convert.getTaxData(next.getTax()));
					this.getPurchasesDet().setDiscount(next.getDiscount());
					this.getPurchasesDet().setCharge(next.getCharge());

					this.insertDetail();
					if (this.purchasesDet == null) {
						this.purchasesDet = new PurchasesDetBean();
					}
				}
				
				// Setting Operation Type
				this.setOperationType("CPED");

			}else{
				// Clean Objects
				this.getPurchasesHead().setBuyConditionData(null);
				this.getPurchasesHead().setBuyTypeData(null);
				this.getPurchasesHead().setCurrencyData(null);
				this.getPurchasesHead().setChangeType(null);
				this.getPurchasesHead().setCostCenterData(null);
				this.getPurchasesHead().setDiscount(null);
				this.getAllOrderDet().clear();
				this.getAllPurchasesDet().clear();
				// Setting Operation Type
				this.setOperationType("CNOR");
				
			}
		} catch (CommonException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// This method process the detail data and insert into a collection
	public void insertDetail() {
		try {
			Boolean canInsert = true;
			// First we validate the form
			if (this.getPurchasesHead().getOrderHeadData() == null){
				this.comAssist.validatePurchaseDet(this.getPurchasesDet());
			}
			System.out.println("Inserting Detail");
			System.out.println("SUPPLY: ".concat(this.getPurchasesDet().getSupplyData().getCod().toString()));
			System.out.println("Bean: ".concat(this.getPurchasesDet().toString()));
			// We Verify if the item exist in the list
			if(this.allPurchasesDet.size() > 0){
				System.out.println("NOT EMPTY LIST: " + this.allPurchasesDet.size());
				for(PurchasesDetBean detBean : this.allPurchasesDet){
					if(this.getPurchasesDet().getSupplyData().getId().equals(detBean.getSupplyData().getId()) 
						&& this.getPurchasesDet().getMeasureUnitData().getId().equals(detBean.getMeasureUnitData().getId())){
						System.out.println("EQUAL: "+ 
								this.getPurchasesDet().getSupplyData().getId() + " == "+ detBean.getSupplyData().getId() + " - " +
								this.getPurchasesDet().getMeasureUnitData().getId() + " == "+ detBean.getMeasureUnitData().getId());
						this.comAssist.generateErrorMsg(
								"El insumo seleccionado ya existe en la grilla",
								"actionform:insDetailBtn");
						canInsert = false;
						break;
					}
				}
				if(canInsert == true){
					this.processDetForInsert();
				}
			}else{
				System.out.println("EMPTY LIST: ");
				this.processDetForInsert();
			}

			
			
			

		} catch (Exception e) {
			// this.facesMessages.add(Severity.ERROR, e.getMessage());
			log.error(e);
		}
	}
		
	public void processDetForInsert(){
		try{
			if (this.getPurchasesDet() == null) {
				System.out.println("Detail Bean is NULL");
			} else {
				// First we calculate the Net Cost
				if(this.getPurchasesDet().getDiscount() == null){
					this.getPurchasesDet().setDiscount(new BigDecimal(0));
				}
				if(this.getPurchasesDet().getCharge() == null){
					this.getPurchasesDet().setCharge(new BigDecimal(0));
				}
				System.out.println("GROSS COST: " + (this.getPurchasesDet().getGrossCost()));
				System.out.println("DISCOUNT: " + (this.getPurchasesDet().getDiscount()));
				System.out.println("CHARGE: " + (this.getPurchasesDet().getCharge()));
				
				// Then we calculate the net cost
				Double netCost = (this.getPurchasesDet().getGrossCost().doubleValue())
							   - (this.getPurchasesDet().getDiscount().doubleValue()) 
							   + (this.getPurchasesDet().getCharge().doubleValue());
				Double netCostRounded = ComAssistant.round(netCost, 5);
				this.getPurchasesDet().setNetCost(new BigDecimal(Double.toString(netCostRounded)));
				
				// Then we calculate the item total based in calculated net cost
				Double itemTotal = (this.getPurchasesDet().getQuantity().doubleValue()) * (this.getPurchasesDet().getNetCost().doubleValue());
				Double itemTotalRounded = ComAssistant.round(itemTotal, 5);
				this.getPurchasesDet().setItemAmount(new BigDecimal(Double.toString(itemTotal)));

				// Processing Tax
				this.comAssist.processTax(this.getPurchasesDet().getTaxData(),this.getPurchasesDet().getItemAmount());

				// Setting tax fields
				this.getPurchasesDet().setTaxedAmount(this.comAssist.getTaxedTotal());
				this.getPurchasesDet().setExemptAmount(this.comAssist.getExemptTotal());
				this.getPurchasesDet().setTaxAmount(this.comAssist.getTaxTotal());

				// Calculating basic quantity
				Double basicQuantities = (this.getPurchasesDet().getMeasureUnitData().getQuantity()) * (this.getPurchasesDet().getQuantity());
				this.getPurchasesDet().setBasicQuantities(basicQuantities);
				System.out.println("AFTER TAXING OPERATION - ".concat(this.getPurchasesDet().getItemAmount().toString()));
				
				// Add the Object into a collection
				if (this.getPurchasesDet().getItemAmount().longValue() <= 0) {
					System.out.println("TOTAL INVALIDO");
				} else {
					this.allPurchasesDet.add(this.getPurchasesDet());
					System.out.println("Collection allPurchasesDet =".concat(this.allPurchasesDet.toString()));
					this.calcHeadAmounts();
					this.setPurchasesDet(null);
					this.setInitVar("S");
				}

			}
			
		}catch (Exception e) {
			// this.facesMessages.add(Severity.ERROR, e.getMessage());
			log.error(e);
		}
	}

	public void calcHeadAmounts() {

		// Initializing Variables
		Double totalAmount = new Double(0);
		Double totalExempt = new Double(0);
		Double totalTax = new Double(0);

		if(allPurchasesDet.isEmpty()){
			this.getPurchasesHead().setTotal(null);
			this.getPurchasesHead().setExemptTotal(null);
			this.getPurchasesHead().setTaxTotal(null);
		}else{
			// Defining an Iterator
			Iterator<PurchasesDetBean> it1 = allPurchasesDet.iterator();

			// Walking trough collection
			while (it1.hasNext()) {
				// Setting the next reg
				PurchasesDetBean nextDet = it1.next();
				System.out.println("Next:".concat(nextDet.toString()));
				// Calculating the addition
				totalAmount += nextDet.getItemAmount().doubleValue();
				totalExempt += nextDet.getExemptAmount().doubleValue();
				totalTax += nextDet.getTaxAmount().doubleValue();
				
			}

			System.out.println("Total amount:".concat(totalAmount.toString()));
			if (totalAmount == null || totalAmount <= 0) {
				System.out.println("Invalid Total:".concat(totalAmount.toString()));
			} else {
				// If addition is not null set the head total
				Double roundedTotalAmount = ComAssistant.round(totalAmount, 5);
				this.getPurchasesHead().setTotal(new BigDecimal(Double.toString(roundedTotalAmount)));
				
			}
			if (totalTax == null || totalTax <= 0) {
				System.out.println("Invalid TotalTax:".concat(totalTax.toString()));
			} else {
				// If addition is not null set the head total
				Double roundedTotalTax = ComAssistant.round(totalTax, 5);
				this.getPurchasesHead().setTaxTotal(new BigDecimal(Double.toString(roundedTotalTax)));
				
			}
			if (totalExempt == null || totalExempt <= 0) {
				System.out.println("Invalid totalExcempt:".concat(totalExempt.toString()));
			} else {
				// If addition is not null set the head total
				Double roundedTotalExempt = ComAssistant.round(totalExempt, 5);
				this.getPurchasesHead().setExemptTotal(new BigDecimal(Double.toString(roundedTotalExempt)));
				
			}
		}
		
	}

	// Used for data saving process
	public void saveNewData() throws ParseException, SQLException {
		// save new data by Bruno - Canapech.
		System.out.println("OPERATION: " + this.getOperationType());
		this.setValidateEntireForm(true);
		Boolean validForm = comAssist.validatePurchaseForm(this.purchasesHead,
				this.allPurchasesDet);
		if (validForm == true) {
			try {
				
				PurchasesHeadBean newPurchaseHead = new PurchasesHeadBean();
				PurchasesDetBean newPurchaseDet = new PurchasesDetBean();
				// RETRIEVING ENTERPRISE AND BRANCH ID
				/*OOOOOOOOOJOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
				 *OOOOOOOOOJOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
				 *EMPRESA Y SUCURSAL SE DEBEN TRAER DEL VALOR DEL FORMULARIO 
				 *NO DIRECTAMENTE DEL USUARIO
				 *CAMBIAR LUEGOOOOOOOOOOOOOOOOOOO
				 * */
				newPurchaseHead.setIdEnt(this.user.getIdEnt());
				newPurchaseHead.setIdBranch(this.user.getDefaultBranch());
				
				if(this.getOperationType().equals("CPED")){
					this.setOrderHead(this.getPurchasesHead().getOrderHeadData());
				}

				// INITIALIZING OBJECTS IN THE NUMBER GENERATION CLASS
				this.numbers.setInitVar("S");
				this.numbers.initData();

				// SETTING FIELDS
				// Invoice Number Fields
				newPurchaseHead.setEstablishment(NullAssistant.checkNullString(this.getPurchasesHead().getEstablishment()));
				newPurchaseHead.setExpedition(NullAssistant.checkNullString(this.getPurchasesHead().getExpedition()));
				newPurchaseHead.setStamping(NullAssistant.checkNullString(this.getPurchasesHead().getStamping()));
				newPurchaseHead.setVoucher(NullAssistant.checkNullString(this.getPurchasesHead().getVoucher()));

				// Other Fields
				newPurchaseHead.setBuyCondition(NullAssistant.checkNullLong(this.getPurchasesHead().getBuyConditionData().getId()));
				newPurchaseHead.setBuyType(NullAssistant.checkNullLong(this.getPurchasesHead().getBuyTypeData().getId()));
				newPurchaseHead.setChangeType(NullAssistant.checkNullDouble(this.getPurchasesHead().getChangeType()));
				newPurchaseHead.setCostCenter(NullAssistant.checkNullLong(this.getPurchasesHead().getCostCenterData().getId()));
				newPurchaseHead.setCurrency(NullAssistant.checkNullLong(this.getPurchasesHead().getCurrencyData().getId()));
				newPurchaseHead.setTaxTotal(NullAssistant.checkNullBigDecimal(this.getPurchasesHead().getTaxTotal()));
				newPurchaseHead.setExemptTotal(NullAssistant.checkNullBigDecimal(this.getPurchasesHead().getExemptTotal()));
				newPurchaseHead.setGravTotal(NullAssistant.checkNullBigDecimal(this.getPurchasesHead().getGravTotal()));
				newPurchaseHead.setDiscount(NullAssistant.checkNullBigDecimal(this.getPurchasesHead().getDiscount()));
				newPurchaseHead.setCharge(NullAssistant.checkNullBigDecimal(this.getPurchasesHead().getCharge()));
				newPurchaseHead.setIdSupplier(NullAssistant.checkNullLong(this.getPurchasesHead().getSupplierData().getId()));
				newPurchaseHead.setTotal(NullAssistant.checkNullBigDecimal(this.getPurchasesHead().getTotal()));
				newPurchaseHead.setIdTypeTrans(NullAssistant.checkNullLong(this.getPurchasesHead().getVoucherData().getId()));
				newPurchaseHead.setIdTypeTransRef(NullAssistant.checkNullLong(this.getPurchasesHead().getIdTypeTransRef()));

				// Date Fields
				newPurchaseHead.setVoucherDate(this.getPurchasesHead().getVoucherDate()); // date of the provider invoice
				newPurchaseHead.setStartDate(DateAssistant.getHoleDateTime()); // date when invoice was generated
				newPurchaseHead.setStatusDate(DateAssistant.getHoleDateTime()); // date
				newPurchaseHead.setStatus("PEND");

				prSrv.saveNewPurchaseHead(newPurchaseHead);

				System.out.println("THIS.ORDERHEAD.GETBUYCONDITIONDATA() = ".concat(this.getPurchasesHead().getBuyConditionData().getId().toString()));
				System.out.println("this.orderHead.getCostCenterData() = ".concat(this.getPurchasesHead().getCostCenterData().getId().toString()));
				System.out.println("this.orderHead.getCurrencyData() = ".concat(this.getPurchasesHead().getCurrencyData().getId().toString()));
				System.out.println("this.orderHead.getChangeType() = "+ this.getPurchasesHead().getChangeType());

				// Retrieving Header Id
				Long idHead = new Long(0);
				idHead = prSrv.getPurchasesHeadIdByEntPurchasesUk(
						newPurchaseHead.getIdEnt(), 
						newPurchaseHead.getIdTypeTrans(), 
						newPurchaseHead.getEstablishment(),
						newPurchaseHead.getExpedition(),
						newPurchaseHead.getVoucher(),
						newPurchaseHead.getIdSupplier());

				System.out.println("HEAD = " + idHead);

				// SAVING DETAIL
				Integer vContador = new Integer(0);
				for (PurchasesDetBean bean : allPurchasesDet) {
					vContador++;

					// Processing Tax
					// this.comAssist.processTax(this.getPurchasesDet().getTaxData(),
					// this.getPurchasesDet().getItemTotal());
					System.out.println("###### vContador  #####".concat(vContador.toString()));

					// Setting Fields
					newPurchaseDet.setIdHead(idHead);
					newPurchaseDet.setItem(new Long(vContador));
					newPurchaseDet.setSupply(bean.getSupplyData().getId());
					newPurchaseDet.setMeasureUnit(bean.getMeasureUnitData().getId());
					newPurchaseDet.setBasicQuantities(bean.getBasicQuantities());
					newPurchaseDet.setOldGrossCost(new BigDecimal(0));
					newPurchaseDet.setGrossCost(bean.getGrossCost());
					newPurchaseDet.setQuantity(bean.getQuantity());
					newPurchaseDet.setTax(bean.getTaxData().getId());
					newPurchaseDet.setDiscount(bean.getDiscount());
					newPurchaseDet.setCharge(bean.getCharge());
					newPurchaseDet.setNetCost(bean.getNetCost());
					newPurchaseDet.setItemAmount(bean.getItemAmount());
					newPurchaseDet.setTaxAmount(bean.getTaxAmount());
					newPurchaseDet.setTaxedAmount(bean.getTaxedAmount());
					newPurchaseDet.setExemptAmount(bean.getExemptAmount());

					prSrv.saveNewPurchaseDet(newPurchaseDet);
					
					if(this.getOperationType().equals("CPED")){
						if(bean.getQuantity().equals(bean.getOrderQuantity())){
							this.getOrderHead().setStatus("FACT");
						}
						orSrv.updateInvoiceQuantities(this.getOrderHead().getId(), new Long(vContador), bean.getQuantity(), this.getOrderHead().getStatus());
					}	
				}
				this.comAssist.generateInfoMsg(
						"Compra Registrada de forma Exitosa",
						"actionform:saveRegBtn");
				this.setValidateEntireForm(false);
				this.cleanData(); // Cleaning Objects
				this.setInitVar("S"); // Setting initialization Flag

			} catch (CommonException e) {
				// TODO: handle exception
				// this.facesMessages.add(Severity.ERROR, e.getMessage());
				System.out.println("NO SE PUDO INSERTAR. ".concat(e
						.getMessage().toString()));

				log.error(e);
			}
		}

	}

	/**
	 * Purchase Query.
	 * 
	 * @throws SQLException
	 * @throws SQLException
	 */

	public void retrieveFilteredPurchases() throws SQLException {
		try {
			Long idSupplier = null;
			String status = null;
			Date voucherDate = null;

			if (this.getPurchaseQueryHead().getSupplierData() != null) {
				idSupplier = this.getPurchaseQueryHead().getSupplierData()
						.getId();
			}
			if (this.getPurchaseQueryHead().getStatus() != null) {
				status = this.getPurchaseQueryHead().getStatus();
			}

			if (this.getPurchaseQueryHead().getVoucherDate() != null) {
				voucherDate = this.getPurchaseQueryHead().getVoucherDate();
				System.out.println("VOUCHER DATE. " + this.getPurchaseQueryHead().getVoucherDate());
			}

			this.setAllPurchaseQueryHead(prSrv.getFilteredPurchases(idSupplier,status, voucherDate));
			
			if(this.allPurchaseQueryHead.isEmpty()){
				this.comAssist.generateInfoMsg("No se encontraron Facturas", "actionform:pQuerySearchBtn");
			}
			
		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}

	}

	public void retrievePendingPurchases(PurchasesHeadBean purchaseHeadp,
			String operation) throws SQLException {
		try {
			Long idSupplier = null;
			Date voucherDate = null;
			String status = new String("PEND");
			if (purchaseHeadp.getSupplierData() != null) {
				idSupplier = purchaseHeadp.getSupplierData().getId();
			}

			if (purchaseHeadp.getVoucherDate() != null) {
				voucherDate = purchaseHeadp.getVoucherDate();
			}
			if (operation.equals("CONFIRM")) {
				this.setAllPurchaseConfHead(prSrv.getPendingPurchases(
						idSupplier, voucherDate, status));
				System.out.println("PENDING PURCHASES LIST CONFIRM: "
						+ this.allPurchaseConfHead);
				if(this.allPurchaseConfHead.isEmpty()){
					this.comAssist.generateInfoMsg("No Existen Facturas con estado Pendiente", "actionform:pConfSearchBtn");
				}
			}

			if (operation.equals("CANCEL")) {
				this.setAllPurchaseCancelHead(prSrv.getPendingPurchases(
						idSupplier, voucherDate, status));
				System.out.println("PENDING PURCHASES LIST CANCEL: "
						+ this.allPurchaseCancelHead);
				if(this.allPurchaseCancelHead.isEmpty()){
					this.comAssist.generateInfoMsg("No Existen Facturas con estado Pendiente", "actionform:pCancelSearchBtn");
				}
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}

	}

	public void retrivePurchaseDet(Long idHead, String operation) {

		try {
			if (operation.equals("QUERY")) {
				this.setAllPurchaseQueryDet(prSrv
						.getPurchaseDetByHeadId(idHead));
				System.out.println("QUERY PURCHASE DET: "
						+ this.allPurchaseQueryDet);
			}
			if (operation.equals("CONFIRM")) {
				this
						.setAllPurchaseConfDet(prSrv
								.getPurchaseDetByHeadId(idHead));
				System.out.println("CONFIRM PURCHASE DET: "
						+ this.allPurchaseConfDet);
			}
			if (operation.equals("CANCEL")) {
				this.setAllPurchaseCancelDet(prSrv
						.getPurchaseDetByHeadId(idHead));
				System.out.println("CANCEL PURCHASE DET: "
						+ this.allPurchaseCancelDet);
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}
	}

	public void retrieveFeesToSuppliersBySupplierId() {
		try {
			Long idSupplier = null;
			if (this.getFeesToSupplierQueryData().getSupplierData() == null) {
				this.comAssist.generateErrorMsg("Seleccione un proveedor",
						"actionform:searchBtn");
			} else {
				idSupplier = this.getFeesToSupplierQueryData().getSupplierData().getId();
				this.setAllFeesToSupplierQueryData(fsSrv
						.getFeesToSuppliersQuery(
								this.user.getIdEnt(), 
								idSupplier));
				System.out.println("FEES TO SUPPLIERS: "
						+ this.getAllFeesToSupplierQueryData().size());
			}
			Iterator<PaymentOrderDetBean> it = allFeesToSupplierQueryData.iterator();
			while(it.hasNext()){
				PaymentOrderDetBean next = it.next();
				System.out.println("FEC-FACTURA: "+ next.getVoucherDate());
				System.out.println("NRO-FACTURA: "+ this.comAssist.getInvoiceNumber(
						next.getEstablishment(), 
						next.getExpedition(), 
						next.getVoucher(), 
						next.getInstalments()));
				System.out.println("SALDO: "+ next.getResiduePaymentOrden());
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}
	}

	public void confirmPurchase() throws SQLException {
		try {
			Boolean noneSelected = true;
			Iterator<PurchasesHeadBean> it = allPurchaseConfHead.iterator();

			while (it.hasNext()) {
				PurchasesHeadBean purchasesHeadBean = it.next();
				if (purchasesHeadBean.getSelected() == true) {
					noneSelected = false;
					System.out.println("antes de confirmar la factura "
							+ purchasesHeadBean.getEstablishment() + "-"
							+ purchasesHeadBean.getExpedition() + "-"
							+ purchasesHeadBean.getVoucher());
					this.prSrv.confirmPurchase(purchasesHeadBean.getId());
					System.out
							.println("despues de confirmar, se commiteo, esta mal peor luego lo vemos :) ");
					/* Actualizar stock y costos */
					System.out
							.println("**** antes de suppliesCostStockProcess ****");
					suppliesCostStockProcess(purchasesHeadBean);
					/* generar cuotas a proveedor */
					System.out
							.println("**** antes de feesToSupplierProcess ****");
					feesToSupplierProcess(purchasesHeadBean);
					System.out
							.println("**** despues de feesToSupplierProcess ****");
				}
				if(!it.hasNext()){
					this.comAssist.generateInfoMsg(
							"Comfirmaci�n realizada con �xito!",
							"actionform:purchaseConfBtn");
				}
			}

			if (noneSelected == true) {
				this.comAssist.generateErrorMsg(
						"Favor seleccione al menos un registro",
						"actionform:purchaseConfBtn");
			} else {
				this.retrievePendingPurchases(this.getPurchaseConfHead(),
						"CONFIRM");
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());
			log.error(e);
		}

	}

	private void suppliesCostStockProcess(PurchasesHeadBean purchasesHeadBean) {
		long operacionStock = 0;
		BigDecimal vAvgCost = new BigDecimal(0);
		VoucherBean vouBean = new VoucherBean();
		System.out.println("antes de ir a consultar voucher "
				+ purchasesHeadBean.getBuyType());

		try {
			vouBean = vouSrv.getVoucherData(purchasesHeadBean.getIdTypeTrans());
			if (vouBean == null) {
				System.out.println("vouBean == null");
				this.comAssist.generateErrorMsg(
						"No existe tipo de comprobante seleccionado",
						"actionform:confirmBtn");
			} else {
				System.out.println("***** vouBean no es nulo : ) *****");
				if (vouBean.getOperateStock().equals("S")) {
					System.out.println("=S=1");
					operacionStock = 1;
				}
				if (vouBean.getOperateStock().equals("R")) {
					System.out.println("=R=-1");
					operacionStock = -1;
				}
				if (vouBean.getOperateStock().equals("N")) {
					System.out.println("=N=0");
					operacionStock = 0;
				}
			}
		} catch (CommonException e) {
			System.out.println("No se ha encontrado getVoucherData ** "
					.concat(e.getMessage().toString()));
			log.error(e);
		}

		/**
		 * Buscamos el valor parametrizado de cantidad quiebre stock por defecto
		 * en parametros generales
		 */
		System.out.println("** buscamos el parametro STOCK_MIN_DEFAULT **");
		GenParamBean genParBean = new GenParamBean();
		GenParamServices genParSrv;
		try {
			genParSrv = new GenParamServices(this.sqlMap.getConfig());
			genParBean = genParSrv.getGenParamBeanByEntAndCod(purchasesHeadBean
					.getIdEnt(), "STOCK_MIN_DEFAULT");
		} catch (CommonException e) {
			System.out
					.println("No se ha encontrado parametros generales STOCK_MIN_DEFAULT ** "
							.concat(e.getMessage().toString()));
			log.error(e);
		}

		if (genParBean == null) {
			/*
			 * Si no existe seteado el registro le agregamos a 15.
			 */
			System.out.println("** STOCK_MIN_DEFAULT==null, 15 default **");
			genParBean.setParamValues("15");
		}

		/**
		 * buscamos la cantidad de la unidad de medida
		 */
		try {
			System.out.println("** unidad de medida **");
			MeasureUnitBean measureUnitBean = new MeasureUnitBean();
			MeasureUnitServices muSrv = new MeasureUnitServices(this.sqlMap
					.getConfig());

			/**
    		 * 
    		 */

			/**
			 * bean y services para insertar o actualizar el stock y los costos
			 */
			System.out.println("** suplyCostStkBean :) **");
			SupplyCostStockBean suplyCostStkBean = new SupplyCostStockBean();
			SupplyCostStockServices supSrv = new SupplyCostStockServices(
					this.sqlMap.getConfig());

			/**
			 * Creamos una coleccion para buscar el detalle de la comprara e ir
			 * insertando en la tabla de costos y stock a partir de la lista
			 * generada en la factura de compra...
			 */
			System.out.println("** purchasesDetList :) **");
			Collection<PurchasesDetBean> purchasesDetList = null;
			PurchasesDetBean purcDetBean = new PurchasesDetBean();
			PurchasesServices purSrv = new PurchasesServices(this.sqlMap
					.getConfig());
			/**
			 * obtenemos el detalle a partir del id de la cabecera de la factura
			 */
			purchasesDetList = purSrv.getPurchaseDetByHeadId(purchasesHeadBean
					.getId());
			Iterator<PurchasesDetBean> it = purchasesDetList.iterator();
			System.out.println("** antes del iterator de  purchasesDetList**");
			while (it.hasNext()) {
				PurchasesDetBean purchasesDetBean = it.next();
				/**
				 * Unique en la tabla de stock y costo son el articulo, la
				 * sucursal y la unidad de medida
				 */
				System.out
						.println("** entramos al while para buscar el registro de getSupplyCostStockData **");
				suplyCostStkBean = supSrv.getSupplyCostStockData(
						purchasesDetBean.getSupply(), purchasesHeadBean
								.getIdBranch(), purchasesDetBean
								.getMeasureUnit());
				measureUnitBean = muSrv.getMeasureUnitData(purchasesDetBean
						.getMeasureUnit());
				if (suplyCostStkBean == null) {
					SupplyCostStockBean suplyCostStkBeanIns = new SupplyCostStockBean();
					SupplyCostStockServices supSrvIns = new SupplyCostStockServices(
							this.sqlMap.getConfig());
					/**
					 * insertar un registro en costo sucursal para el insumo, la
					 * sucursal y la unidad de medida
					 */
					System.out
							.println("***# no existe el registro en suplyCostStkBean, lo creamos purchasesDetBean.getSupply()= ***"
									+ purchasesDetBean.getSupply());
					// suplyCostStkBean.setSupply(purchasesDetBean.getSupply());
					suplyCostStkBeanIns.setSupply(purchasesDetBean.getSupply());
					System.out.println("*** 1");
					System.out.println("purchasesDetBean.getSupply()= "
							+ purchasesDetBean.getSupply());
					suplyCostStkBeanIns.setIdBranch(purchasesHeadBean
							.getIdBranch());
					System.out.println("*** 2");
					suplyCostStkBeanIns.setIdMeasureUnit(purchasesDetBean
							.getMeasureUnit());
					System.out.println("*** 3");
					suplyCostStkBeanIns
							.setStock(purchasesDetBean.getQuantity());
					/**
					 * por defecto enviamos el campo de cantidad para la
					 * cantidad física Una vez realizado el inventario esto debe
					 * de ser actualizado con el valor del inventario para este
					 * articulo, unidad de medida y sucursal
					 */
					System.out.println("*** 4");
					suplyCostStkBeanIns.setRealStock(purchasesDetBean
							.getQuantity()
							* operacionStock);
					System.out.println("*** 5");
					suplyCostStkBeanIns.setMinStock(new Double(genParBean
							.getParamValues()));
					System.out.println("*** 6");
					suplyCostStkBeanIns.setBasicStock(purchasesDetBean
							.getQuantity()
							* measureUnitBean.getQuantity() * operacionStock);
					System.out.println("*** 7");
					suplyCostStkBeanIns.setIdCurrency(purchasesHeadBean
							.getCurrency());
					System.out.println("*** 8");
					suplyCostStkBeanIns.setNetCost(purchasesDetBean
							.getNetCost());
					System.out.println("*** 9");
					suplyCostStkBeanIns.setGrossCost(purchasesDetBean
							.getGrossCost());
					/**
					 * --------------------------------------------------------
					 * --- -- CALCULO DE COSTO PROMEDIO. --
					 * ----------------------
					 * ------------------------------------- -- REFERENCIAS: --
					 * --
					 * ---------------------------------------------------------
					 * -- CM = Cantidad del Movimiento. -- -- CT = Costo de
					 * Transferencia. -- -- CP = Costo Promedio Actual. -- -- EX
					 * = Existencia Actual. --
					 * ----------------------------------
					 * ------------------------- -- FORMULA: ( ( CM * CT ) + (
					 * CP * EX ) ) / ( EX + CM ); --
					 * ----------------------------
					 * -------------------------------
					 */
					System.out.println("*** 10");
					vAvgCost = new BigDecimal(purchasesDetBean.getQuantity() * measureUnitBean.getQuantity());
					System.out.println("*** 11");
					vAvgCost = new BigDecimal(vAvgCost.doubleValue()* purchasesDetBean.getNetCost().doubleValue());
					System.out.println("*** 12");
					vAvgCost = new BigDecimal(vAvgCost.doubleValue() + (0 * 0));
					System.out.println("*** 13");
					vAvgCost = new BigDecimal(vAvgCost.doubleValue() / (0 + (purchasesDetBean.getQuantity() * measureUnitBean.getQuantity())));
					System.out.println("*** 14");
					suplyCostStkBeanIns.setAverageCost(vAvgCost);
					System.out.println("*** 15");
					supSrvIns.saveNewSupplyCostStock(suplyCostStkBeanIns);
					System.out.println("*** 16");
				} else {
					/*
					 * alterar los valores para insertar el stock y los costos
					 * nuevos
					 */
					suplyCostStkBean.setStock(suplyCostStkBean.getStock() + (purchasesDetBean.getQuantity() * operacionStock));
					suplyCostStkBean.setBasicStock(suplyCostStkBean.getBasicStock()+ (purchasesDetBean.getQuantity()* measureUnitBean.getQuantity() * operacionStock));

					suplyCostStkBean.setNetCost(purchasesDetBean.getNetCost());
					suplyCostStkBean.setGrossCost(purchasesDetBean.getGrossCost());
					/**
					 * --------------------------------------------------------
					 * --- -- CALCULO DE COSTO PROMEDIO. --
					 * ----------------------
					 * ------------------------------------- -- REFERENCIAS: --
					 * --
					 * ---------------------------------------------------------
					 * -- CM = Cantidad del Movimiento. -- -- CT = Costo de
					 * Transferencia. -- -- CP = Costo Promedio Actual. -- -- EX
					 * = Existencia Actual. --
					 * ----------------------------------
					 * ------------------------- -- FORMULA: ( ( CM * CT ) + (
					 * CP * EX ) ) / ( EX + CM ); --
					 * ----------------------------
					 * -------------------------------
					 */
					vAvgCost = new BigDecimal(purchasesDetBean.getQuantity()
							* measureUnitBean.getQuantity());
					vAvgCost = new BigDecimal(vAvgCost.doubleValue()
							* purchasesDetBean.getNetCost().doubleValue());
					vAvgCost = new BigDecimal(
							vAvgCost.doubleValue()
									+ (suplyCostStkBean.getAverageCost()
											.doubleValue() * suplyCostStkBean
											.getStock()));
					/**
					 * Podría dar el caso de que la cantidad existente fuese la
					 * misma que la unidad básica en movimiento (transacción)
					 * pero de signo contrario, dicho caso daría un valor cero.
					 * Entonces tendríamos un error de división por cero
					 */
					if ((suplyCostStkBean.getStock() + (purchasesDetBean
							.getQuantity() * measureUnitBean.getQuantity())) != 0) {
						vAvgCost = new BigDecimal(
								vAvgCost.doubleValue()
										/ (suplyCostStkBean.getStock() + (purchasesDetBean
												.getQuantity() * measureUnitBean
												.getQuantity())));
					}

					suplyCostStkBean.setAverageCost(vAvgCost);
					supSrv.updateSupplyCostStock(suplyCostStkBean);
				}
			}

			/**
    		 * 
    		 */
		} catch (CommonException e) {
			System.out.println("error en feroz try catch ** ".concat(e
					.getMessage().toString()));
			log.error(e);
		}

	}

	public void feesToSupplierProcess(PurchasesHeadBean purchasesHeadBean) {
		System.out.println("Entramos en feesToSupplierProcess ** ");
		Integer vCantCuo = new Integer(0);
		System.out.println("## 1");
		BigDecimal vAmountOfFee = new BigDecimal(0);
		System.out.println("## 2");
		BigDecimal vAmountOfFeeAc = new BigDecimal(0);
		/**
		 * traer los decimales de la moneda. traer numero de cuotas, periodo de
		 * la tabla de condiciones de compra loopear por la cantidad de cuotas
		 * que tenga la condicion de compra insertar un registro por cada loop
		 */
		try {
			System.out.println("## 3");
			CurrencyBean currencyBean = new CurrencyBean();
			CurrencyServices crSrv = new CurrencyServices(this.sqlMap.getConfig());
			currencyBean = crSrv.getCurrencyData(purchasesHeadBean.getCurrency());
			System.out.println("## 4");
			BuyConditionBean buyCondBean = new BuyConditionBean();
			BuyConditionServices bcSrv = new BuyConditionServices(this.sqlMap.getConfig());
			buyCondBean = bcSrv.getBuyConditionById(purchasesHeadBean.getBuyCondition());
			System.out.println("## 5");

			if (!buyCondBean.getInstalments().equals(0)) {
				vAmountOfFee = purchasesHeadBean.getTotal().divide(
						new BigDecimal(buyCondBean.getInstalments()), 0,
						RoundingMode.HALF_UP);
			} else {
				vAmountOfFee = purchasesHeadBean.getTotal();
			}

			System.out.println("## 7");
			String vTipo = new String("");

			System.out.println("## 8");
			if (buyCondBean.getInstalments().equals(0)) {
				vTipo = "CONTADO";
				vCantCuo = 0;
			} else {
				vTipo = "CREDITO";
				vCantCuo = 1;
			}
			Date vEndDate = new Date();
			vEndDate = purchasesHeadBean.getVoucherDate();

			while (buyCondBean.getInstalments() >= vCantCuo) {

				FeesToSuppliersBean feesToSupplierBean = new FeesToSuppliersBean();
				FeesToSupplierServices feesToSupplierSrv = new FeesToSupplierServices(
						this.sqlMap.getConfig());
				System.out.println("## 6");
				System.out.println("## dentro del while ** ");
				// try {
				System.out.println("dentro del while. getInstalments()" + buyCondBean.getInstalments() + " - vCantCuo= " + vCantCuo);
				System.out.println("antes if. vAmountOfFee= " + vAmountOfFee + " - vAmountOfFeeAc= " + vAmountOfFeeAc);
				if (buyCondBean.getInstalments().equals(vCantCuo)) {
					System.out.println("buyCondBean.getInstalments() == (vCantCuo)");
					vAmountOfFee = purchasesHeadBean.getTotal().subtract(vAmountOfFeeAc);
				} else {
					System.out.println("buyCondBean.getInstalments() != (vCantCuo)");
					vAmountOfFeeAc = vAmountOfFeeAc.add(vAmountOfFee);
				}
				System.out.println("despues if. vAmountOfFee= " + vAmountOfFee + " - vAmountOfFeeAc= " + vAmountOfFeeAc);
				System.out.println("## 9");
				System.out.println("## 10");
				feesToSupplierBean.setInsDate(DateAssistant.getHoleDateTime());
				feesToSupplierBean.setInsDatetime(DateAssistant.getHoleDateTime());
				System.out.println("## 12");
				vEndDate = DateAssistant.getDatePlusDay(vEndDate, buyCondBean.getPeriod());
				feesToSupplierBean.setEndDate(vEndDate);
				feesToSupplierBean.setIdProv(purchasesHeadBean.getIdSupplier());
				System.out.println("## 11");
				feesToSupplierBean.setIdTrans(purchasesHeadBean.getId());
				feesToSupplierBean.setIdTypeTrans(purchasesHeadBean.getIdTypeTrans());
				System.out.println("## 13");
				feesToSupplierBean.setInstalments((vTipo == "CONTADO") ? 0 : vCantCuo);
				System.out.println("## 14");
				feesToSupplierBean.setAmountOfFee(vAmountOfFee);
				feesToSupplierBean.setBalanceOfFee(vAmountOfFee);
				System.out.println("## 15");
				feesToSupplierSrv.saveNewFeesToSuppliers(feesToSupplierBean);
				System.out.println("## 16");
				feesToSupplierBean = null;
				feesToSupplierSrv = null;
				vCantCuo++;
				System.out.println("## 17");
				// } catch (ParseException e) {
				// System.out.println("error insertando cuotas ** ".concat(e.getMessage().toString()+" error insertCuotas"));
				// log.error(e);
				// }
				System.out.println("## 18");

			}
		} catch (CommonException e) {
			System.out
					.println("error CommonException primer try catch en procesa cuotas prov ** "
							.concat(e.getMessage().toString()));
			log.error(e);
		} catch (ParseException e2) {
			System.out.println("error ParseException primer try catch en procesa cuotas prov ** ".concat(e2.getMessage().toString()));
			log.error(e2);
		}
	}

	public void cancelPurchase() throws SQLException {
		try {
			Boolean noneSelected = true;
			Iterator<PurchasesHeadBean> it = allPurchaseCancelHead.iterator();

			while (it.hasNext()) {
				PurchasesHeadBean next = it.next();
				if (next.getSelected() == true) {
					noneSelected = false;
					this.prSrv.cancelPurchase(next.getId());
				}
				if(!it.hasNext()){
					this.comAssist.generateInfoMsg(
							"Anulaci�n realizada con �xito!",
							"actionform:cancelPurchaseBtn");
				}
			}

			if (noneSelected == true) {
				this.comAssist.generateErrorMsg(
						"Favor seleccione al menos un registro",
						"actionform:cancelPurchaseBtn");
			} else {
				this.retrievePendingPurchases(this.getPurchaseCancelHead(),
						"CANCEL");
			}

		} catch (CommonException e) {
			// TODO: handle exception
			System.out.println("NO SE PUDO RECUPERAR. " + e.getMessage());

			log.error(e);
		}

	}

	// Retrieving data for updating
	public void dataToEdit(Long id) {
		System.out.println("id = ".concat(id.toString()));

	}

	public void dataToEditUpd() throws ParseException {

	}

	// falta el metodo void dataToDelete(Long id)

	// Getters and Setters

	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public boolean isEditMode() {
		return editMode;
	}

	public void setEditMode(boolean editMode) {
		this.editMode = editMode;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public UsersBean getUser() {
		return this.user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}

	public BuyConditionBean getBuyCondition() {
		return buyCondition;
	}

	public void setBuyCondition(BuyConditionBean buyCondition) {
		this.buyCondition = buyCondition;
	}

	public BuyConditionServices getBcSrv() {
		return bcSrv;
	}

	public void setBcSrv(BuyConditionServices bcSrv) {
		this.bcSrv = bcSrv;
	}

	public Collection<BuyConditionBean> getAllBuyCondition() {
		return allBuyCondition;
	}

	public void setAllBuyCondition(Collection<BuyConditionBean> allBuyCondition) {
		this.allBuyCondition = allBuyCondition;
	}

	public OrderHeadBean getOrderHead() {
		return orderHead;
	}

	public void setOrderHead(OrderHeadBean orderHead) {
		this.orderHead = orderHead;
	}

	public OrderDetBean getOrderDet() {
		return orderDet;
	}

	public void setOrderDet(OrderDetBean orderDet) {
		this.orderDet = orderDet;
	}

	public Collection<OrderDetBean> getAllOrderDet() {
		return allOrderDet;
	}

	public void setAllOrderDet(Collection<OrderDetBean> allOrderDet) {
		this.allOrderDet = allOrderDet;
	}

	public Boolean getCanSave() {
		return canSave;
	}

	public static void setCanSave(Boolean arg) {
		canSave = arg;
	}

	public PurchasesHeadBean getPurchasesHead() {
		return purchasesHead;
	}

	public void setPurchasesHead(PurchasesHeadBean purchasesHead) {
		this.purchasesHead = purchasesHead;
	}

	public PurchasesDetBean getPurchasesDet() {
		return purchasesDet;
	}

	public void setPurchasesDet(PurchasesDetBean purchasesDet) {
		this.purchasesDet = purchasesDet;
	}

	public List<PurchasesDetBean> getAllPurchasesDet() {
		return allPurchasesDet;
	}

	public void setAllPurchasesDet(List<PurchasesDetBean> allPurchasesDet) {
		this.allPurchasesDet = allPurchasesDet;
	}

	public PurchasesHeadBean getPurchaseQueryHead() {
		return purchaseQueryHead;
	}

	public void setPurchaseQueryHead(PurchasesHeadBean purchaseQueryHead) {
		this.purchaseQueryHead = purchaseQueryHead;
	}

	public PurchasesDetBean getPurchaseQueryDet() {
		return purchaseQueryDet;
	}

	public void setPurchaseQueryDet(PurchasesDetBean purchaseQueryDet) {
		this.purchaseQueryDet = purchaseQueryDet;
	}

	public Collection<PurchasesHeadBean> getAllPurchaseQueryHead() {
		return allPurchaseQueryHead;
	}

	public void setAllPurchaseQueryHead(
			Collection<PurchasesHeadBean> allPurchaseQueryHead) {
		this.allPurchaseQueryHead = allPurchaseQueryHead;
	}

	public Collection<PurchasesDetBean> getAllPurchaseQueryDet() {
		return allPurchaseQueryDet;
	}

	public void setAllPurchaseQueryDet(
			Collection<PurchasesDetBean> allPurchaseQueryDet) {
		this.allPurchaseQueryDet = allPurchaseQueryDet;
	}

	public PurchasesHeadBean getPurchaseCancelHead() {
		return purchaseCancelHead;
	}

	public void setPurchaseCancelHead(PurchasesHeadBean purchaseCancelHead) {
		this.purchaseCancelHead = purchaseCancelHead;
	}

	public PurchasesDetBean getPurchaseCancelDet() {
		return purchaseCancelDet;
	}

	public void setPurchaseCancelDet(PurchasesDetBean purchaseCancelDet) {
		this.purchaseCancelDet = purchaseCancelDet;
	}

	public Collection<PurchasesHeadBean> getAllPurchaseCancelHead() {
		return allPurchaseCancelHead;
	}

	public void setAllPurchaseCancelHead(
			Collection<PurchasesHeadBean> allPurchaseCancelHead) {
		this.allPurchaseCancelHead = allPurchaseCancelHead;
	}

	public Collection<PurchasesDetBean> getAllPurchaseCancelDet() {
		return allPurchaseCancelDet;
	}

	public void setAllPurchaseCancelDet(
			Collection<PurchasesDetBean> allPurchaseCancelDet) {
		this.allPurchaseCancelDet = allPurchaseCancelDet;
	}

	public PurchasesHeadBean getPurchaseConfHead() {
		return purchaseConfHead;
	}

	public void setPurchaseConfHead(PurchasesHeadBean purchaseConfHead) {
		this.purchaseConfHead = purchaseConfHead;
	}

	public PurchasesDetBean getPurchaseConfDet() {
		return purchaseConfDet;
	}

	public void setPurchaseConfDet(PurchasesDetBean purchaseConfDet) {
		this.purchaseConfDet = purchaseConfDet;
	}

	public Collection<PurchasesHeadBean> getAllPurchaseConfHead() {
		return allPurchaseConfHead;
	}

	public void setAllPurchaseConfHead(
			Collection<PurchasesHeadBean> allPurchaseConfHead) {
		this.allPurchaseConfHead = allPurchaseConfHead;
	}

	public Collection<PurchasesDetBean> getAllPurchaseConfDet() {
		return allPurchaseConfDet;
	}

	public void setAllPurchaseConfDet(
			Collection<PurchasesDetBean> allPurchaseConfDet) {
		this.allPurchaseConfDet = allPurchaseConfDet;
	}

	public FeesToSuppliersBean getFeesToSupplierQuery() {
		return feesToSupplierQuery;
	}

	public void setFeesToSupplierQuery(FeesToSuppliersBean feesToSupplierQuery) {
		this.feesToSupplierQuery = feesToSupplierQuery;
	}

	public Collection<FeesToSuppliersBean> getAllFeesToSupplierQuery() {
		return allFeesToSupplierQuery;
	}

	public void setAllFeesToSupplierQuery(
			Collection<FeesToSuppliersBean> allFeesToSupplierQuery) {
		this.allFeesToSupplierQuery = allFeesToSupplierQuery;
	}

	public String getOperationType() {
		return operationType;
	}

	public void setOperationType(String operationType) {
		this.operationType = operationType;
	}

	public Boolean getSelectedAll() {
		return selectedAll;
	}

	public void setSelectedAll(Boolean selectedAll) {
		this.selectedAll = selectedAll;
	}

	public modalSelectHolder getSelectHolder() {
		return selectHolder;
	}

	public void setSelectHolder(modalSelectHolder selectHolder) {
		this.selectHolder = selectHolder;
	}

	public Integer getScrollerPage() {
		return scrollerPage;
	}

	public void setScrollerPage(Integer scrollerPage) {
		this.scrollerPage = scrollerPage;
	}

	public PaymentOrderHeadBean getFeesToSupplierQueryData() {
		return feesToSupplierQueryData;
	}

	public void setFeesToSupplierQueryData(
			PaymentOrderHeadBean feesToSupplierQueryData) {
		this.feesToSupplierQueryData = feesToSupplierQueryData;
	}

	public Collection<PaymentOrderDetBean> getAllFeesToSupplierQueryData() {
		return allFeesToSupplierQueryData;
	}

	public void setAllFeesToSupplierQueryData(
			Collection<PaymentOrderDetBean> allFeesToSupplierQueryData) {
		this.allFeesToSupplierQueryData = allFeesToSupplierQueryData;
	}

	public Boolean getValidateEntireForm() {
		return validateEntireForm;
	}

	public void setValidateEntireForm(Boolean validateEntireForm) {
		this.validateEntireForm = validateEntireForm;
	}


	
	
	
}
